﻿namespace WinnerCMS.Data
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    
    using System.Linq;
    using System.Text;
    using WinnerCMS.Common;
    using WinnerCMS.Model;

    /// <summary>
    /// 单位
    /// </summary>
    public class UnitDal
    {
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model"></param>
        public void Add(Unit model)
        {
            using (Entities db = new Entities())
            {
                db.Units.Add(model); 
                db.SaveChangesAsync().Wait();
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        public void Edit(Unit model)
        {
            using (Entities db = new Entities())
            {
                db.Units.Attach(model);
                db.Entry(model).State = EntityState.Modified;
                db.SaveChangesAsync().Wait();
            }
        }
        /// <summary>
        /// 绑定数据
        /// </summary>
        /// <returns></returns>
        public IList<Unit> BindList()
        {
            using (Entities db = new Entities())
            {
                return db.Units.ToList();
            }
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="ids"></param>
        public void Delete(int[] ids)
        {
            using (Entities db = new Entities())
            {
                var q = db.Units.Where(x => ids.Contains(x.Id)).ToList();
                q.ForEach(x => db.Units.Remove(x));
                db.SaveChangesAsync().Wait();
            }
        }
        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>

        public Unit GetInfo(int Id)
        {
            using (Entities db = new Entities())
            {
                return db.Units.Where(x => x.Id == Id).FirstOrDefault();
            }
        }

        #region 绑定分页数据
        /// <summary>
        /// 绑定分页数据
        /// </summary>
        /// <param name="pp"></param>
        /// <returns></returns>
        public IList<Unit> BindList(PagingParam pp)
        {
            using (Entities db = new Entities())
            {
                var query = from x in db.Units
                            select x;
                pp.RecordCount = query.Count();

                return query.OrderByDescending(x => x.Id).Skip(pp.Skip).Take(pp.PageSize).ToList();
            }
        }
        #endregion
    }
}

